package com.party.business.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.NumberUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.party.business.domain.*;
import com.party.business.service.*;
import com.party.common.annotation.Log;
import com.party.common.annotation.RepeatSubmit;
import com.party.common.config.RuoYiConfig;
import com.party.common.core.controller.BaseController;
import com.party.common.core.domain.AjaxResult;
import com.party.common.core.domain.entity.SysDept;
import com.party.common.core.domain.entity.SysDictData;
import com.party.common.core.domain.entity.SysUser;
import com.party.common.core.domain.model.LoginUser;
import com.party.common.core.domain.model.RegisterBody;
import com.party.common.core.page.TableDataInfo;
import com.party.common.enums.BusinessType;
import com.party.common.exception.ServiceException;
import com.party.common.utils.*;
import com.party.common.utils.poi.ExcelUtil;
import com.party.system.domain.SysConfig;
import com.party.system.service.ISysConfigService;
import com.party.system.service.ISysDeptService;
import com.party.system.service.ISysPostService;
import com.party.system.service.ISysUserService;
import org.apache.commons.lang3.ArrayUtils;
import org.aspectj.weaver.loadtime.Aj;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.rmi.ServerException;
import java.rmi.server.ExportException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 网站接口
 */
@RestController
@RequestMapping("/webApi")
public class TWebApiController extends BaseController {

    @Autowired
    private ITLbImageService tLbImageService;


    @Autowired
    private ITNoticeService tNoticeService;


    @Autowired
    private ITNewsService tNewsService;


    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ITFjFileService tFjFileService;

    @Autowired
    private ISysUserService userService;


    @Autowired
    private ITKcTypeService kcTypeService;


    @Autowired
    private ITTwxxService tTwxxService;


    /**
     * 注册协议和隐私政策  关于我们
     */
    @GetMapping("/nologin/twxxlist")
    public AjaxResult twxxlist(TTwxx tTwxx) {
        List<TTwxx> list = tTwxxService.selectTTwxxList(tTwxx);
        return AjaxResult.success(list);
    }


    @Autowired
    private ISysConfigService configService;

    /**
     * 客服电话   客服微信号
     */

    @GetMapping("/nologin/getxtpzList")
    public AjaxResult getxtpzList() {
        SysConfig sysConfig = new SysConfig();
        List<SysConfig> sysConfigs = configService.selectConfigList(sysConfig);
        return AjaxResult.success(sysConfigs);

    }

    /**
     * 轮播图列表
     */
    @GetMapping("/nologin/getLbImageList")
    public AjaxResult getLbImageList(TLbImage tLbImage) {
        List<TLbImage> list = tLbImageService.selectTLbImageList(tLbImage);
        return AjaxResult.success(list);
    }


    /**
     * 课程类型列表
     */
    @GetMapping("/nologin/getKcTypeList")
    public AjaxResult getKcTypeList(TKcType kcType) {
        List<TKcType> tKcTypes = kcTypeService.selectTKcTypeList(kcType);
        return AjaxResult.success(tKcTypes);
    }


    @Autowired
    private ITKcService tKcService;


    /**
     * 课程列表
     */
    @GetMapping("/getKcList")
    public TableDataInfo getKcList(TKc kc) {
        startPage();
        List<TKc> tKcs = tKcService.selectTKcListApp(kc);
        return getDataTable(tKcs);
    }


    /**
     * 课程详情
     */
    @GetMapping(value = "/getkcDetail/{id}")
    public AjaxResult getkcDetail(@PathVariable("id") String id) {
        return AjaxResult.success(tKcService.selectTKcById(id));
    }


    @Autowired
    private ITKcviewRecordService tKcviewRecordService;


    /**
     * 保存课程记录
     */
    @PostMapping("/addKcRecord")
    public AjaxResult addKcRecord(@RequestBody TKcviewRecord tKcviewRecord) {
        tKcviewRecord.setUserId(SecurityUtils.getUserIdStr());
        tKcviewRecordService.save(tKcviewRecord);
        return success();
    }


    @Autowired
    private ITKsTypeService tKsTypeService;

    /**
     * 考试类型列表
     */
    @GetMapping("/nologin/getKsTypeList")
    public AjaxResult getKsTypeList(TKsType vo) {
        List<TKsType> tKsTypes = tKsTypeService.selectTKsTypeList(vo);
        return AjaxResult.success(tKsTypes);
    }


    @Autowired
    private ITKsService tKsService;


    @Autowired
    private ISysPostService postService;

    /**
     * 考试列表
     */
    @GetMapping("/getKsList")
    public TableDataInfo getKsList(TKs vo) {
        startPage();
        List<TKs> tKs = tKsService.selectTKsListApp(vo);
        return getDataTable(tKs);
    }


    /**
     * 考试统计数量--- 未考  已考  重考
     */
    @GetMapping("/getKsFxData")
    public AjaxResult getKsFxData() {
        TKs ks = new TKs();
        ks.setKsType("1");
        List<TKs> yk_tKs = tKsService.selectTKsListApp(ks);
        ks.setKsType("2");
        List<TKs> wk_tKs = tKsService.selectTKsListApp(ks);
        ks.setKsType("3");
        List<TKs> ck_tKs = tKsService.selectTKsListApp(ks);
        HashMap<String, Object> map = new HashMap<>();
        map.put("yk", yk_tKs.size());
        map.put("wk", wk_tKs.size());
        map.put("ck", ck_tKs.size());
        return AjaxResult.success(map);
    }

    @Autowired
    private ITKcviewFinishService tKcviewFinishService;

    /**
     * 保存课程完成记录
     */
    @PostMapping("addkcFinishRecord")
    public AjaxResult addkcFinishRecord(@RequestBody TKcviewFinish vo) {

        TKcviewFinish  kcviewFinish=new TKcviewFinish();
        kcviewFinish.setUserId(SecurityUtils.getUserIdStr());
        kcviewFinish.setKcId(vo.getKcId());
        List<TKcviewFinish> tKcviewFinishes = tKcviewFinishService.selectTKcviewFinishList(kcviewFinish);
        if(CollectionUtil.isEmpty(tKcviewFinishes)){
            vo.setUserId(SecurityUtils.getUserIdStr());
            tKcviewFinishService.save(vo);
        }
        return success();
    }


    /**
     * 课程统计数量--- 已学  未学
     */
   @GetMapping("/getKcFxData")
    public AjaxResult getKcFxData(String  kcType) {
        TKc kc = new TKc();
        // 已学习
        kc.setKcStatus("1");
        kc.setKcType(kcType);
        List<TKc> tKc_yx = tKcService.selectTKcListApp(kc);
        // 未学习
        kc.setKcStatus("2");
        kc.setKcType(kcType);
        List<TKc> tKc_wx = tKcService.selectTKcListApp(kc);
        HashMap<String, Object> map = new HashMap<>();
        map.put("yk", tKc_yx.size());
        map.put("wk", tKc_wx.size());
        map.put("all", tKc_yx.size()+tKc_wx.size());
        return AjaxResult.success(map);
    }

    /**
     * 考试详情
     */
    @GetMapping(value = "/getKsDetail/{id}")
    public AjaxResult getKsDetail(@PathVariable("id") String id) {
        return AjaxResult.success(tKsService.selectTKsById(id));
    }

    @Autowired
    private ITKsQuestionService ksQuestionService;
    @Autowired
    private ITKsRecordService ksRecordService;

    @Autowired
    private ITQuestionOptionService questionOptionService;

    @Autowired
    private ITKsRecordDetailService tKsRecordDetailService;

    /**
     * 提交试卷
     */
    @RepeatSubmit
    @Transactional
    @PostMapping("/updateSaveKsRecord")
    public AjaxResult updateSaveKsRecord(@RequestBody TKsRecord vo) {
        vo.setUserId(SecurityUtils.getUserIdStr());
        BigDecimal score = BigDecimal.ZERO;
        Long rightNum = 0L;
        Long wdNum = 0L;
        List<TKsQuestion> questionList = vo.getQuList();
        List<TKsRecordDetail> recordDetailList = new ArrayList<>();
        for (int i = 0; i < questionList.size(); i++) {
            TKsQuestion ks_qu_vo = questionList.get(i);
            String ks_qu_id = ks_qu_vo.getId();
            TKsQuestion ksquestion = ksQuestionService.getById(ks_qu_id);
            BigDecimal qu_score = ksquestion.getScore();
            String userAnswer = ks_qu_vo.getUserAnswer();
            String rightAndErr = "";
            if (StringUtils.isEmpty(userAnswer)) {
                wdNum = wdNum + 1;
                rightAndErr = "false";
            } else {
                rightAndErr = isRightAndErr(ks_qu_vo);
                if ("true".equals(rightAndErr)) {
                    // 答对
                    rightNum = rightNum + 1;
                    score = score.add(qu_score == null ? BigDecimal.ZERO : qu_score);
                } else {
                }
            }
            TKsRecordDetail ksRecordDetail = new TKsRecordDetail();
            ksRecordDetail.setQuId(ksquestion.getQuId());
            ksRecordDetail.setUserAnswer(ks_qu_vo.getUserAnswer());
            ksRecordDetail.setKsId(vo.getKsId());
            ksRecordDetail.setKsQuId(ks_qu_id);
            ksRecordDetail.setIsRight(rightAndErr);
            recordDetailList.add(ksRecordDetail);

        }
        int size = questionList.size();
        vo.setTotalNum(Long.valueOf(size));
        vo.setErrorNum(Long.valueOf(size) - rightNum);
        vo.setRightNum(rightNum);
        // 计算正确率
        BigDecimal rightLv = NumberUtil.div(rightNum, Long.valueOf(size), 2);
        vo.setRightLv(rightLv + "");
        vo.setScore(score);
        vo.setDetailList(recordDetailList);
        ksRecordService.save(vo);
        recordDetailList.forEach(ksRecordDetail -> {
            ksRecordDetail.setKsRecordId(vo.getId());
        });
        tKsRecordDetailService.saveBatch(recordDetailList);
        return AjaxResult.success(vo);
    }


    /**
     * 试卷考试记录详情
     */
    @GetMapping("/getKsRecordDetail")
    public AjaxResult getKsRecordDetail(TKsRecord vo) {
        String id = vo.getId();
        TKsRecord record = ksRecordService.getById(id);
        String ksId = record.getKsId();
        TKsRecordDetail detail = new TKsRecordDetail();
        detail.setKsRecordId(id);
        List<TKsRecordDetail> recordDetails = tKsRecordDetailService.selectTKsRecordDetailList(detail);
        for (int i = 0; i < recordDetails.size(); i++) {
            TKsRecordDetail ksRecordDetail = recordDetails.get(i);
            String ksQuId = ksRecordDetail.getKsQuId();
            // 试题信息
            TKsQuestion question = ksQuestionService.selectTKsQuestionById(ksQuId);
            TQuestionOption questionOption = new TQuestionOption();
            questionOption.setQuId(question.getQuId());
            List<TQuestionOption> tQuestionOptions = questionOptionService.selectTQuestionOptionList(questionOption);
            question.setQuestionOptionList(tQuestionOptions);
            recordDetails.get(i).setQuestion(question);

        }
        record.setDetailList(recordDetails);
        TKs tKs = tKsService.selectTKsByIdApp(ksId);
        record.setKsxx(tKs);
        return AjaxResult.success(record);
    }

    public String isRightAndErr(TKsQuestion ksQuestion) {
        String isRight = "";
        // 简答题
        //  用户答案  用户传入正确的选型  如 多选题 传入 B,C
        List<String> user_answer = new ArrayList<String>();
        String userAnswer = ksQuestion.getUserAnswer();
        // 用户没有 选择答案 直接判错
        if (StringUtils.isEmpty(userAnswer)) {
            isRight = "false";
            return isRight;
        }
        if (!StringUtils.isEmpty(userAnswer)) {
            String[] split = userAnswer.split(",");
            user_answer = Arrays.asList(split);
        }
        TQuestionOption tQuAnswer = new TQuestionOption();
        tQuAnswer.setQuId(ksQuestion.getQuId());
        List<String> fight_anList = new ArrayList<>();
        List<TQuestionOption> tQuAnswers = questionOptionService.selectTQuestionOptionList(tQuAnswer);
        for (int j = 0; j < tQuAnswers.size(); j++) {
            TQuestionOption quAnswer = tQuAnswers.get(j);
            // true
            String isRight1 = quAnswer.getIsRight();
            //  A  B  C  D
            String options = quAnswer.getOptions();
            // 1单选  2 判断
            if ("true".equals(isRight1)) {
                fight_anList.add(options);
            }

        }
        boolean aBoolean = this.compareByContainsAll(user_answer, fight_anList);
        if (aBoolean) {
            isRight = "true";
        } else {
            isRight = "false";
        }

        return isRight;
    }

    public Boolean compareByContainsAll(List<String> list, List<String> list2) {
        boolean flag = false;
        if (list.size() == list2.size()) {
            if (list.containsAll(list2)) {
                flag = true;
            }
        }
        return flag;
    }


//    /**
//     * 查询人员通过角色
//     */
//
//    @GetMapping("/getUserlistByRole")
//    public AjaxResult getUserlistByRole(SysUser user) {
//        List<SysUser> list = userService.selectUserListByRole(user);
//        return AjaxResult.success(list);
//    }
//
//
//    /**
//     * 查询数据字典
//     */
//    @GetMapping("/nologin/getDict")
//    public AjaxResult getDict(String key) {
//        List<SysDictData> dictCache = DictUtils.getDictCache(key);
//        return AjaxResult.success(dictCache);
//    }
//
//    /**
//     * 查询所有的字典
//     */
//    @GetMapping("/nologin/getAllDict")
//    public AjaxResult getAllDict(String key) {
//        HashMap<String, Object> hashMap = new HashMap<>();
//        List<SysDictData> award_type = DictUtils.getDictCache("award_type");
//        List<SysDictData> skill_type = DictUtils.getDictCache("skill_type");
//        List<SysDictData> zy_type = DictUtils.getDictCache("zy_type");
//        List<SysDictData> bm_type = DictUtils.getDictCache("bm_type");
//        List<SysDictData> sf_type = DictUtils.getDictCache("sf_type");
//
//        hashMap.put("award_type", award_type);
//        hashMap.put("skill_type", skill_type);
//        // 专业
//        hashMap.put("zy_type", zy_type);
//        // 报名类型
//        hashMap.put("bm_type", bm_type);
//        // 身份类型
//        hashMap.put("sf_type", sf_type);
//
//        return AjaxResult.success(hashMap);
//    }
//
//
//    /**
//     * 轮播图列表
//     */
//    @GetMapping("/nologin/list")
//    public AjaxResult list(TLbImage tLbImage) {
//        List<TLbImage> list = tLbImageService.selectTLbImageList(tLbImage);
//        return AjaxResult.success(list);
//    }
//
//    /**
//     * 通知公告列表
//     */
//    @GetMapping("/nologin/tNotice/list")
//    public TableDataInfo tNoticelist(TNotice tNotice) {
//        startPage();
//        List<TNotice> list = tNoticeService.selectTNoticeList(tNotice);
//        return getDataTable(list);
//    }
//
//    /**
//     * 通知公告--详情
//     */
//    @GetMapping(value = "/nologin/tNotice/{id}")
//    public AjaxResult gettNoticeInfo(@PathVariable("id") String id) {
//        return AjaxResult.success(tNoticeService.getById(id));
//    }
//
//
//    /**
//     * 获取赛事新闻列表
//     */
//
//    @GetMapping("/nologin/tNews/list")
//    public TableDataInfo list(TNews tNews) {
//        startPage();
//        List<TNews> list = tNewsService.selectTNewsList(tNews);
//        return getDataTable(list);
//    }
//
//
//    /**
//     * 获取赛事新闻详细信息
//     */
//    @GetMapping(value = "/nologin/tNews/{id}")
//    public AjaxResult getTNewsInfo(@PathVariable("id") String id) {
//        return AjaxResult.success(tNewsService.getById(id));
//    }
//
//
//
//
//
//
//
//
//
//    @Autowired
//    private TWebApiService webApiService;
//
//
//    @Autowired
//    private ISysDeptService deptService;
//
//
//    /**
//     * 学校和院系列表
//     */
//    @GetMapping("/nologin/getDeptlist")
//    public AjaxResult getDeptlist(SysDept dept) {
//        List<SysDept> depts = deptService.selectDeptListQuery(dept);
//        return AjaxResult.success(depts);
//    }
//

    /**
     * 用户个人信息
     */
    @GetMapping("/getUserInfo")
    public AjaxResult getInfo() {
        Long userId = SecurityUtils.getUserId();
        SysUser sysUser = sysUserService.selectUserByIdApp(userId);
        return AjaxResult.success(sysUser);
    }

    /**
     * 用户个人信息--修改
     */
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("updateUser")
    public AjaxResult updateUser(@RequestBody SysUser user) {
        user.setUpdateBy(getUsername());
        user.setUserId(SecurityUtils.getUserId());
        return toAjax(sysUserService.updateUserApp(user));
    }

    /**
     * 用户个人信息--用户注销
     */
    @DeleteMapping("/removeUser")
    public AjaxResult removeUser() {
        String username = SecurityUtils.getUsername();
        if ("admin".equals(username)) {
            return AjaxResult.error("超级管理员不能注销");
        }
        Long[] userIds = {SecurityUtils.getUserId()};
        return toAjax(userService.deleteUserAppByIds(userIds));
    }
    /**
     * 用户个人信息--用户课程时长
     */
    @GetMapping("/getuserKsTimeData")
    public AjaxResult getuserKsTimeData() {
        HashMap<String, Object> hashMap = new HashMap<>();
        TKcviewRecord kcviewRecord = new TKcviewRecord();
        kcviewRecord.setUserId(SecurityUtils.getUserIdStr());
        List<TKcviewRecord> tKcviewRecords = tKcviewRecordService.selectTKcviewRecordList(kcviewRecord);
        // 统计times 之和
        Long sumTimes = tKcviewRecords.stream().mapToLong(TKcviewRecord::getTimes).sum();
        // 转成分钟
        Long usertimes = sumTimes / 60;
        SysConfig sysConfig = new SysConfig();
        sysConfig.setConfigKey("viewtime");
        List<SysConfig> sysConfigs = configService.selectConfigList(sysConfig);
        Long totalTime = Long.parseLong(sysConfigs.get(0).getConfigValue());
        hashMap.put("usertimes", usertimes);
        hashMap.put("totaltime", totalTime);
        return AjaxResult.success(hashMap);

    }

    /**
     * 对比人脸
     */
    @GetMapping("/getFaceCom")
    public   AjaxResult  getFaceCom(String imgUrl) throws Exception {
        String filePath = RuoYiConfig.getProfile();
         imgUrl = imgUrl.replace("profile/", "");
        imgUrl=filePath+imgUrl;
        System.out.println(imgUrl);
        SysUser sysUser = userService.selectUserByIdApp(SecurityUtils.getUserId());
        if(StringUtils.isEmpty(sysUser.getAvatar())){
            return  AjaxResult.error("请上传头像");
        }
        String avatar = filePath+sysUser.getAvatar().replace("profile/", "");
        Boolean aBoolean = CompareFace.compareFace(imgUrl, avatar);
        if(aBoolean){
            return  AjaxResult.success("对比成功");
        }else{
            return  AjaxResult.error("人脸识别失败");
        }

    }


}
